<?php
// public/documents.php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();

$title = "Documents | JO & COS RMS";

// --- Initialize message ---
$msg = null;
$type = "success";

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_doc'])) {
    try {
        $stmt = $pdo->prepare("DELETE FROM documents WHERE id=?");
        $stmt->execute([$_POST['id']]);
        header("Location: documents.php?msg=Document+deleted+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: documents.php?msg=Error:+Could+not+delete&type=danger");
        exit;
    }
}

// Handle remarks update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_remark'])) {
    try {
        $stmt = $pdo->prepare("UPDATE documents SET remarks=? WHERE id=?");
        $stmt->execute([$_POST['remarks'], $_POST['id']]);
        header("Location: documents.php?msg=Remark+saved+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: documents.php?msg=Error:+Could+not+update+remark&type=danger");
        exit;
    }
}
// --- Expected document types ---
$docTypes = [
  'Medical Certificate',
  'NBI/Police Clearance',
  'PRC License/Rating',
  'Transcript of Records',
  'PSA Birth Certificate',
  'Certificate of Employment',
  'Publication Records'
];

// Fetch all employees who have uploaded at least one document
$stmt = $pdo->query("
    SELECT DISTINCT e.id, e.full_name, e.college_office, e.job_title
    FROM employees e
    JOIN documents d ON e.id = d.employee_id
    ORDER BY e.full_name ASC
");
$employees = $stmt->fetchAll(PDO::FETCH_ASSOC);



include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<section class="content">
  <div class="container-fluid">

    <?php if (isset($_GET['msg'])): ?>
      <div class="alert alert-<?= htmlspecialchars($_GET['type'] ?? 'info') ?> alert-dismissible fade show" role="alert">
        <?= htmlspecialchars($_GET['msg']) ?>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
      </div>
    <?php endif; ?>

    <div class="card">
      <div class="card-body table-responsive">
        <table id="docsTable" class="table table-bordered table-striped nowrap" style="width:100%">
          <thead>
            <tr>
              <th>Employee</th>
              <th>Uploaded Files</th>
              <th>Lacking Documents</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($employees as $emp): ?>
              <?php
              // Get this employee’s uploaded documents
              $stmt = $pdo->prepare("SELECT * FROM documents WHERE employee_id = ?");
              $stmt->execute([$emp['id']]);
              $docs = $stmt->fetchAll(PDO::FETCH_ASSOC);

              // Extract uploaded doc types
              $uploadedTypes = array_column($docs, 'doc_type');

              // Find which documents are missing
              $missing = array_diff($docTypes, $uploadedTypes);
              ?>
              <tr>
                <td>
                  <strong><?= htmlspecialchars($emp['full_name']) ?></strong><br>
                  <small><?= htmlspecialchars($emp['college_office']) ?> | <?= htmlspecialchars($emp['job_title']) ?></small>
                </td>

                <!-- Uploaded documents -->
                <td>
                  <?php if ($docs): ?>
                    <ul class="mb-0">
                      <?php foreach ($docs as $doc): ?>
                        <li>
                          <strong><?= htmlspecialchars($doc['doc_type']) ?>:</strong>
                          <a href="../<?= htmlspecialchars($doc['file_path']) ?>" target="_blank" class="btn btn-sm btn-outline-info">
                            <i class="fas fa-eye"></i> View
                          </a>
                          <a href="../<?= htmlspecialchars($doc['file_path']) ?>" download class="btn btn-sm btn-outline-success">
                            <i class="fas fa-download"></i> Download
                          </a>
                        </li>
                      <?php endforeach; ?>
                    </ul>
                  <?php else: ?>
                    <em>No uploads yet</em>
                  <?php endif; ?>
                </td>

                <!-- Missing documents -->
                <td>
                  <?php if (!empty($missing)): ?>
                    <ul class="mb-0 text-danger">
                      <?php foreach ($missing as $m): ?>
                        <li><?= htmlspecialchars($m) ?></li>
                      <?php endforeach; ?>
                    </ul>
                  <?php else: ?>
                    <span class="text-success">Complete ✅</span>
                  <?php endif; ?>
                </td>

                <!-- Actions -->
                <td>
                  <form method="post" style="display:inline;">
                    <input type="hidden" name="id" value="<?= $emp['id'] ?>">
                    <button type="submit" name="delete_all_docs" class="btn btn-sm btn-danger" 
                            onclick="return confirm('Delete all uploaded files for this employee?');">
                      <i class="fas fa-trash"></i> Delete All
                    </button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</section>


<?php include __DIR__ . '/../includes/footer.php'; ?>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap4.min.css"/>

<script>
$(function () {
  $('#docsTable').DataTable({
    responsive: true,
    autoWidth: false
  });

  // Auto-hide alerts after 3 seconds
  setTimeout(() => {
    $(".alert").alert('close');
  }, 3000);
});
</script>
